#!/usr/bin/env python


# Copyright (c) 2011 by Kenneth Dixon
#
# GNU General Public Licence (GPL)
# 
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307  USA

import Properties as pr
import urllib2
import time
import os
import logging

class IPCam():

    def __init__(self):
        self.logger = logging.getLogger(pr.LOGGER_NAME)    
    
    def getSnapshots(self):
        self.logger.info("Getting Snapshots from IP Camera")
        snapShotURL = "http://"+pr.CAM_IP+":"+pr.CAM_PORT+pr.CAM_SNAPSHOT_PAGE+"?user="+pr.CAM_USER+"&pwd="+pr.CAM_PASSWORD
        
        dateTimeString = time.strftime("%Y%m%d%H%M%S",time.localtime())
        snapshotLeafDir = pr.CAM_SNAPSHOT_ROOT_DIR+"/"+dateTimeString
        os.makedirs(snapshotLeafDir)
        
        opener = urllib2.build_opener()
        page = opener.open(snapShotURL)
        for n in range(pr.CAM_SNAPSHOTS_NUMBER):
            page = opener.open(snapShotURL)
            snapshot = page.read()
            filename = snapshotLeafDir+"/"+time.strftime("%Y%m%d%H%M%S",time.localtime())+"-"+str(n)+".jpg"
            fout = open(filename, "wb")
            fout.write(snapshot)
            fout.close()  
            time.sleep(pr.CAM_SNAPSHOTS_DELAY_SEC)
        
        self.logger.info("Returning Snapshot Directory: "+snapshotLeafDir)
        return snapshotLeafDir


#For Testing Only ********************************
#def main():
#    print "main"
#    myIPCam = IPCam()
#    resultingDir = myIPCam.getSnapshots()
#    print resultingDir
    
#main()
    